import os
import uuid
import random

import requests
from langchain_core.tools import tool

from ai_resume_generator.resume_docx_generator import generate_resume_from_ai_response
import json
import re
import ast
from boss import settings
from rag_test.hybrid_search import hybrid_search_labor_law
from user.models import JobInfo, WorkExperience


@tool(
    description="""
    用于劳动法相关的问题回答,
    输入参数:question,代表用户的问题,必填,示例:未签劳动合同能要赔偿吗？
    返回结果:检索出来并格式化的内容,如果检索出来的数据为空, 则返回的是“未检索到直接相关的劳动法条文，将基于通用劳动法原则回答”
    """
)
def labor_law_tool(question: str) -> str:
    """
    咨询劳动法
    """
    # 调用混合检索函数，获取Top3相关法条（可调整top_k）
    rag_results = hybrid_search_labor_law(
        query_text=question,
        top_k=3,  # 返回3条最相关法条，平衡精度与回答长度
        filter_conditions=None  # 不限制章节，全量检索（需限定章节可添加条件）
    )
    print("混合检索rag_results:", rag_results)
    # 处理检索结果：格式化法条内容，作为大模型回答依据
    if not rag_results:
        legal_basis = "未检索到直接相关的劳动法条文，将基于通用劳动法原则回答："
        return legal_basis
    else:
        legal_basis = "根据《中华人民共和国劳动合同法》相关规定：\n"
        for idx, result in enumerate(rag_results, 1):
            metadata = result["metadata"]
            # 提取核心信息：法条号+标题+内容（截取前200字避免过长）
            article_info = (
                f"{idx}. {metadata['article_num']}《{metadata['article_title']}》\n"
                f"   内容：{metadata['content_clean']}...\n"
            )
            legal_basis += article_info

        return legal_basis


@tool(
    description="""
    用于学历信息验证,
    输入参数:vcode,代表用户输入的学历信息验证码,必填,验证码的规则是:大写字母,小写字母,数字构成,8到20位,示例:AM4X8VJR3BN9FC1C
    返回结果:验证结果，如果验证成功，则返回的是学历信息，如果验证失败，则返回的是错误信息
    """
)
def education_tool(vcode: str) -> str:
    api_url = f"https://www.apimy.cn/api/xxw/bgcx?key={os.getenv("MY_XXW_BGCX_API_KEY")}"
    response = requests.post(api_url, data={'vcode': vcode.upper()})
    # 获取响应内容
    result = response.json()
    print(result)
    print(type(result))
    if result["code"] == 200:
        # 验证成功的情况
        data = result.get('data', {})
        return f"""✅ 学历验证成功！

            👤 **基本信息**
            姓名：{data.get('姓名', 'N/A')}
            性别：{data.get('性别', 'N/A')}
            出生日期：{data.get('出生日期', 'N/A')}

            🎓 **学历信息**
            学校：{data.get('学校名称', 'N/A')}
            专业：{data.get('专业', 'N/A')}
            学历层次：{data.get('层次', 'N/A')}
            学制：{data.get('学制', 'N/A')}
            毕业时间：{data.get('毕（结）业日期', 'N/A')}

            📋 **验证详情**
            证书编号：{data.get('证书编号', 'N/A')}
            学历类别：{data.get('学历类别', 'N/A')}
            学习形式：{data.get('学习形式', 'N/A')}
            毕业状态：{data.get('毕（结）业', 'N/A')}

            该学历信息真实有效，可以放心录用。"""
    else:
        # 验证失败的情况
        return f"""❌ 学历验证失败

               失败原因：{result.get('msg', '未知错误')}

               建议：
               • 请检查验证码是否输入正确
               • 确认验证码是否已过期
               • 如有疑问，可要求候选人重新提供验证码"""


@tool(
    description="""
    用于查询个人简历信息,
    输入参数:desired_position,代表用户期望的职位,必填,示例:软件工程师
    输入参数:desired_city,代表用户期望的职位,必填,示例:上海
    输入参数:desired_money,代表用户期望的职位,必填,示例:10k
    返回结果:候选人的信息
    """
)
def resume_tool(desired_position: str, desired_city: str, desired_money) -> dict:
    user_base_info = {
        "jiben_info": {
            "name": "",
            "sex": "",
            "birthdate": "",
            "phone": "",
            "email": "",
            "description": "",
            "education": "",
            "current_status": ""

        },
        "desired": {
            "desired_position": "",
            "desired_money": "",
            "desired_city": ""
        },
        "work_experience": [

        ],
        "skills": {

        }
    }
    user_id = 1
    user_base_info["desired"]["desired_position"] = desired_position
    user_base_info["desired"]["desired_city"] = desired_city
    user_base_info["desired"]["desired_money"] = desired_money
    from user.models import User
    user = User.objects.get(id=user_id)
    user_base_info["jiben_info"]["name"] = user.username
    user_base_info["jiben_info"]["phone"] = user.phone
    user_base_info["jiben_info"]["email"] = user.email

    education_map = {
        1: '初中以下',
        2: '初中',
        3: '中专'
    }

    current_status_map = {
        1: '在职看机会',
        2: '离职'
    }

    sex_map = {
        1: '男',
        2: '女'
    }

    job_info = JobInfo.objects.filter(user=user).first()
    user_base_info["jiben_info"]["birthdate"] = job_info.birthdate
    user_base_info["jiben_info"]["description"] = job_info.description
    user_base_info["jiben_info"]["education"] = education_map.get(job_info.education)
    user_base_info["jiben_info"]["current_status"] = current_status_map.get(job_info.current_status)
    user_base_info["jiben_info"]["sex"] = sex_map.get(job_info.sex)

    work_experience = WorkExperience.objects.filter(job_info=job_info).all()

    industry_map = {
        1: "IT互联网",
        2: "金融",
        3: "医疗",
        4: "教育",
        5: "广告",
        6: "咨询",
        7: "建筑",
        8: " Transport",
        9: "能源",
        10: "政府",
        11: "其他"
    }

    work_experience_list = []
    for work_exp in work_experience:
        # 处理日期格式
        start_date = work_exp.start_date.strftime('%Y-%m-%d') if work_exp.start_date else ""
        end_date = work_exp.end_date.strftime('%Y-%m-%d') if work_exp.end_date else "至今"

        work_experience_info = {
            "company": work_exp.company,
            "description": work_exp.description,
            "end_date": end_date,
            "start_date": start_date,
            "position": work_exp.position,
            "salary_range": work_exp.salary_range,
            "industry": industry_map.get(work_exp.industry),
        }

        work_experience_list.append(work_experience_info)

    user_base_info["work_experience"] = work_experience_list

    skills = _generate_skills_data()

    user_base_info['skills'] = skills

    # 数据评分,自己完善,判断,10,15 算出来的分数/总分 >80%
    score = 0
    if user_base_info['jiben_info']['name']:
        score += 1
    if user_base_info['jiben_info']['phone']:
        score += 1

    work_experience_text = []
    for work_exp in user_base_info['work_experience']:
        work_experience_info = {
            "公司名": work_exp.get('company'),
            "开始时间": work_exp.get('start_date'),
            "结束时间": work_exp.get('end_date'),
            "职位": work_exp.get('position'),
            "工作描述": work_exp.get('description'),
            "所属行业": work_exp.get('industry'),
            "薪资范围": work_exp.get('salary_range')
        }

        work_experience_text.append(work_experience_info)

    return {
        "基本信息": {
            "姓名": user_base_info['jiben_info']['name'],
            "手机号": user_base_info['jiben_info']['phone'],
            "性别": user_base_info['jiben_info']['sex'],
            "出生日期": user_base_info['jiben_info']['birthdate'],
            "学历信息": user_base_info['jiben_info']['education'],
            "邮箱": user_base_info['jiben_info']['email'],
            "当前状态": user_base_info['jiben_info']['current_status'],
            "个人评价": user_base_info['jiben_info']['description']
        },
        "求职意向": {
            "岗位": user_base_info['desired']['desired_position'],
            "期望薪资": user_base_info['desired']['desired_money'],
            "城市": user_base_info['desired']['desired_city']
        },
        "工作经历": work_experience_text,
        "专业技能": user_base_info['skills']
    }


def _generate_skills_data():
    """生成技能数据，格式为包含技能等级的字典"""
    skills_pool = [
        'Python', 'Java', 'JavaScript', 'React', 'Vue.js', 'Angular',
        'Node.js', 'Django', 'Flask', 'Spring Boot', 'MySQL', 'PostgreSQL',
        'MongoDB', 'Redis', 'Docker', 'Kubernetes', 'AWS', 'Azure',
        'Git', 'Jenkins', 'Linux', 'HTML', 'CSS', 'TensorFlow', 'PyTorch',
        'FASTAPI', 'CSS3', 'HTML5', 'Bootstrap', 'jQuery', 'TypeScript',
        'Next.js', 'Nuxt.js', 'Express', 'Koa', 'Electron', 'React Native',
        'Flutter', 'Swift', 'Kotlin', 'ReactVR', 'Unity3D', 'C#', 'C++',
        'Go', 'Rust', 'Scala', 'Elixir', 'Phoenix', 'Ruby', 'Rails',
        'PHP', 'Laravel', 'Symfony', 'Java Spring', 'MyBatis', 'Hibernate',
        'Oracle', 'SQL Server', 'SQLite', 'Cassandra', 'Neo4j', 'HBase',
        'Elasticsearch', 'Solr', 'Kibana', 'Logstash', 'Nginx', 'Apache',
        'Tomcat', 'Jboss', 'WebLogic', 'OpenShift', 'OpenStack', 'VMware',
        'Ansible', 'Puppet', 'Chef', 'Terraform', 'CloudFormation', 'Prometheus',
        'Grafana', 'Zabbix', 'Splunk', 'Datadog', 'New Relic', 'AppDynamics',
        'Selenium', 'JMeter', 'LoadRunner', 'Postman', 'SoapUI', 'Cucumber',
        'Jenkins X', 'GitLab CI', 'Travis CI', 'CircleCI', 'Bamboo', 'TeamCity',
        'Maven', 'Gradle', 'Ant', 'SonarQube', 'Checkmarx', 'Fortify',
        'OAuth', 'JWT', 'SAML', 'OpenID Connect', 'LDAP', 'Active Directory',
        'TCP/IP', 'HTTP/HTTPS', 'DNS', 'DHCP', 'BGP', 'OSPF', 'MPLS',
        'Firewall', 'IDS/IPS', 'VPN', 'SIEM', 'DDoS防护', '渗透测试',
        '区块链', '以太坊', 'Hyperledger', '智能合约', 'Solidity', 'Web3.js',
        '机器学习', '深度学习', '自然语言处理', '计算机视觉', '数据挖掘', '强化学习'
    ]

    skill_levels = ['精通', '熟练', '了解', '基础']

    # 从技能池中随机选择最多100个技能
    selected_skills = random.sample(
        skills_pool,
        min(10, len(skills_pool))
    )

    # 为每个技能分配一个等级
    skills_dict = {}
    for skill in selected_skills:
        skills_dict[skill] = random.choice(skill_levels)

    return skills_dict


def _clean_ai_response(response_text):
    """
    清理AI返回的内容，移除markdown代码块标记
    """
    import re

    # 移除markdown代码块标记
    cleaned = re.sub(r'^```json\s*', '', response_text.strip())
    cleaned = re.sub(r'\s*```$', '', cleaned)

    # 移除可能的其他代码块标记
    cleaned = re.sub(r'^```\s*', '', cleaned)
    cleaned = re.sub(r'\s*```$', '', cleaned)

    return cleaned.strip()



@tool(
    description="""
    根据候选人的基本信息生成一份简历，
    参数是resume_info候选人的简历信息，返回结果为Word文档下载链接
    """
)
def generate_resume_tool(resume_info: str) -> str:
    print(f"收到简历生成请求: {resume_info}")
    # 清理AI返回的内容，移除markdown代码块标记
    cleaned_output = _clean_ai_response(resume_info)
    # 生成文件名
    # username = user_base_info['jiben_info']['name'] or f"user_{user_id}"
    filename = f"{uuid.uuid4()}_简历.docx"
    # 生成Word文档
    file_path = generate_resume_from_ai_response(cleaned_output, filename)

    # 获取相对路径用于前端访问
    relative_path = os.path.relpath(file_path, settings.MEDIA_ROOT)
    download_url = f"{settings.MEDIA_URL}{relative_path}"
    # 获取完整的下载地址
    full_download_url = f"{settings.SITE_URL}{download_url}"
    print(f"简历文档生成成功: {file_path}")
    result = f"""
              ✅简历文档生成成功
              ⬇️<a href="{full_download_url}" target="_blank">点击下载</a>
              """

    return result


if __name__ == '__main__':
    # print(labor_law_tool("未签劳动合同能要赔偿吗？"))
    print(education_tool("A7FKKV3C4Q40RWGD"))
